<template>
  <editor-layout class="edit" @ok="handleOk"
                 v-on="$listeners"
                 v-loading="loading"
                 :loading="saveLoading"
  >
    <group-tags :data="list" @select="onSelect" v-model="currTag" @add="onAdd" @addOk="onAddOk" @remove="onRemove"/>
    <div style="margin-top: 30px; width: 50%;" v-show="currTag">
      <el-form ref="form" size="small" :model="model" :rules="rules" label-width="110px">
        <el-form-item label="分组名称:" prop="name">
          <el-input v-model="model.name" clearable/>
        </el-form-item>
      </el-form>
    </div>
  </editor-layout>
</template>

<script>
import groupTags from '@/components/report/image/group-tags'
import {
  postImagegroupSave,
  postImagegroupDelete,
  postImagegroupListUserAll
} from '@/api/image-group'

export default {
  name: 'group-edit',
  cnName: 'group-edit',
  components: {groupTags},
  data() {
    return {
      loading: false,
      saveLoading: false,
      list: [],
      currTag: '',
      model: {
        id: '',
        name: ''
      },
      rules: {
        name: [{required: true, message: '必填项'}]
      }
    }
  },
  methods: {
    load() {
      postImagegroupListUserAll({type: 'image'}).then(res => {
        this.loading = false
        const list = res || []
        this.list = list.map(o => {
          return {
            label: o.name,
            value: o.id
          }
        })
      })
    },
    onSelect(item) {
      this.model.name = item.label
      this.model.id = item.value
    },
    handleOk() {
      if(this.currTag === '') {
        return
      }
      this.$refs.form.validate(ok => {
        if (!ok) return
        this.loading = true
        postImagegroupSave(this.model).then(res => {
          this.loading = false
          this.load()
        })
      })
    },
    onAdd() {

    },
    onAddOk(name) {
      if(!name) return
      this.loading = true
      postImagegroupSave({name, type: 'image'}).then(res => {
        this.loading = false
        this.load()
      })
    },
    onRemove(item, index) {

      this.$confirm('此操作将会删除分组下的图片，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.currTag = ''
        postImagegroupDelete([item.value]).then(_ => {
          this.load()
        })
      })

    }
  },
  mounted() {
    this.load()
  }
}
</script>
